package cn.shengchao.qywx.remote.rpc;

import cn.hutool.core.collection.CollUtil;
import cn.shengchao.base.enums.DisEnableStatusEnum;
import cn.shengchao.examstar.rpc.base.PageResult;
import cn.shengchao.examstar.rpc.wecom.api.CustomerServiceGroupApi;
import cn.shengchao.examstar.rpc.wecom.cs.WeComLockCs;
import cn.shengchao.examstar.rpc.wecom.req.*;
import cn.shengchao.examstar.rpc.wecom.resp.CustomerServiceGroupDetailVo;
import cn.shengchao.examstar.rpc.wecom.resp.CustomerServiceGroupVo;
import cn.shengchao.qywx.infrastrure.po.QywxSysCsGroup;
import cn.shengchao.qywx.infrastrure.po.QywxSysCsGroupUserbind;
import cn.shengchao.qywx.infrastrure.service.QywxRuleGroupService;
import cn.shengchao.qywx.infrastrure.service.QywxSysCsGroupService;
import cn.shengchao.qywx.infrastrure.service.QywxSysCsGroupUserbindService;
import cn.shengchao.qywx.infrastrure.service.QywxUserSysbindService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import top.continew.starter.core.exception.BaseException;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: examstarapi
 * @description: 客服组业务实现
 * @author: Xiong weiqiang
 * @create: 2025-04-09 15:37
 */
@DubboService
@RequiredArgsConstructor
public class CustomerServiceGroupDubboApi implements CustomerServiceGroupApi {
    private final QywxSysCsGroupService qywxSysCsGroupService;
    private final QywxSysCsGroupUserbindService qywxSysCsGroupUserbindService;
    private final QywxUserSysbindService qywxUserSysbindService;
    private final QywxRuleGroupService  qywxRuleGroupService;
    private final RedisTemplate<String,Object> redisTemplate;
    @Override
    public PageResult<CustomerServiceGroupVo> queryCustomerServiceGroupPage(CustomerServiceGroupPageQuery customerServiceGroupPageQuery) {
        Page<Object> page= PageHelper.startPage(customerServiceGroupPageQuery.getPage(), customerServiceGroupPageQuery.getSize());
        List<CustomerServiceGroupVo> csGroupPageList=qywxSysCsGroupService.selectCsGroupPageList(customerServiceGroupPageQuery);
        return PageResult.of(page.getTotal(), csGroupPageList);
    }

    @Override
    public void changeCustomerServiceGroupState(CustomerServiceGroupStateDto customerServiceGroupStateDto) {
        DisEnableStatusEnum disEnableStatusEnum=DisEnableStatusEnum.getByValue(customerServiceGroupStateDto.getEnableStatus());
        if (disEnableStatusEnum==null){throw new BaseException("编辑客服组状态时发生错误：客服组上传状态错误");}
        qywxSysCsGroupService.update(Wrappers.lambdaUpdate(QywxSysCsGroup.class)
                .eq(QywxSysCsGroup::getId, customerServiceGroupStateDto.getGroupId())
                .set(QywxSysCsGroup::getStatus, disEnableStatusEnum.getValue())
        );
    }
    @Transactional
    @Override
    public void saveCustomerServiceGroup(CustomerServiceGroupSaveDto customerServiceGroupSaveDto) {
        QywxSysCsGroup qywxSysCsGroup=null;
        if (customerServiceGroupSaveDto.getGroupId()==null){
            qywxSysCsGroup=new QywxSysCsGroup();
            qywxSysCsGroup.setCsGroupName(customerServiceGroupSaveDto.getGroupName());
            qywxSysCsGroup.setStatus(customerServiceGroupSaveDto.getEnableStatus());
            qywxSysCsGroupService.saveOrUpdate(qywxSysCsGroup);
        }else {
            qywxSysCsGroup=qywxSysCsGroupService.getById(customerServiceGroupSaveDto.getGroupId());
            qywxSysCsGroup.setCsGroupName(customerServiceGroupSaveDto.getGroupName());
            qywxSysCsGroup.setStatus(customerServiceGroupSaveDto.getEnableStatus());
            qywxSysCsGroupService.updateById(qywxSysCsGroup);
            qywxSysCsGroupUserbindService.remove(Wrappers.lambdaQuery(QywxSysCsGroupUserbind.class).eq(QywxSysCsGroupUserbind::getCsGroupId,qywxSysCsGroup.getId()));
            String key=WeComLockCs.getRedisKeyForCsGroupUsers(customerServiceGroupSaveDto.getGroupId().toString());
            //换人删除缓存
            if (redisTemplate.hasKey(key)) {
                redisTemplate.delete(key);
                System.out.println("删除了客服组用户缓存"+key);
            }else{
                System.out.println("没有删除了客服组用户缓存"+key);
            }
        }
        if (CollUtil.isNotEmpty(customerServiceGroupSaveDto.getServiceWeComAccountIds())){
            List<QywxSysCsGroupUserbind> csGroupUserbindList=new ArrayList<>();
            for (String serviceWeComAccountId : customerServiceGroupSaveDto.getServiceWeComAccountIds()) {
                QywxSysCsGroupUserbind qywxSysCsGroupUserbind=new QywxSysCsGroupUserbind();
                qywxSysCsGroupUserbind.setCsGroupId(qywxSysCsGroup.getId());
                qywxSysCsGroupUserbind.setQywxUserId(serviceWeComAccountId);
                csGroupUserbindList.add(qywxSysCsGroupUserbind);
            }
            qywxSysCsGroupUserbindService.saveBatch(csGroupUserbindList);
        }
    }

    @Override
    public CustomerServiceGroupDetailVo getCustomerServiceGroupDetail(Long groupId) {
        QywxSysCsGroup qywxSysCsGroup=qywxSysCsGroupService.getById(groupId);
        if (qywxSysCsGroup!=null){
            CustomerServiceGroupDetailVo customerServiceGroupDetailVo=new CustomerServiceGroupDetailVo();
            customerServiceGroupDetailVo.setGroupName(qywxSysCsGroup.getCsGroupName());
            customerServiceGroupDetailVo.setEnableStatus(qywxSysCsGroup.getStatus());
            customerServiceGroupDetailVo.setGroupId(qywxSysCsGroup.getId());
            List<CustomerServiceUserState> customerServiceUserStates=qywxSysCsGroupUserbindService.listCustomerServiceUserBindByQuery(groupId);
            customerServiceGroupDetailVo.setCsUserStateList(customerServiceUserStates);
            return customerServiceGroupDetailVo;
        }
        return null;
    }
    @Transactional
    @Override
    public void delCustomerServiceGroupDetail(Long groupId) {
        long count=qywxRuleGroupService.countUsedRuleGroup(groupId);
        if (count>0){
            throw new BaseException("删除失败：该客服组已被使用");
        }
        qywxSysCsGroupUserbindService.remove(Wrappers.lambdaQuery(QywxSysCsGroupUserbind.class).eq(QywxSysCsGroupUserbind::getCsGroupId,groupId));
        qywxSysCsGroupService.removeById(groupId);
    }

    @Override
    public List<CustomerServiceUserState> listWeComUserByQuery(CsUserQuery csUserQuery) {
        return qywxUserSysbindService.listCustomerServiceUserByQuery(csUserQuery);
    }
}